package com.yupi.shortchain.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.yupi.shortchain.Listener.DemoDataListener;
import com.yupi.shortchain.common.BaseResponse;
import com.yupi.shortchain.common.ResultUtils;
import com.yupi.shortchain.model.dto.file.DemoData;
import com.yupi.shortchain.service.UrlRelateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * 单文件分片上传
 * 上传文件  分片
 * 合并
 * easy excel 读取 List
 * 批量转短链
 * 批量插入数据库
 */
@RestController
@RequestMapping("/upload")
@Slf4j
//@CrossOrigin(origins = "http://localhost:63342/")
@CrossOrigin(origins = "http://localhost:5173")
public class SignalFileUploadController {

    private static final String UPLOAD_DIR = "uploads/";
    @Resource
    private UrlRelateService urlRelateService;

    @PostMapping("/uploadChunk")
    public BaseResponse<Boolean> handleFileChunkUpload(@RequestParam("file") MultipartFile file,
                                        @RequestParam("chunk") int chunk,
                                        @RequestParam("totalChunks") int totalChunks,
                                        @RequestParam("fileName") String fileName
                                        ) {
        try {
            // 创建上传目录
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            //前端进行分片


            // 保存分片文件
            File chunkFile = new File(UPLOAD_DIR + fileName + ".part" + chunk);

            FileUtils.writeByteArrayToFile(chunkFile, file.getBytes());

            log.info("is Login  : {}", StpUtil.isLogin());

            // 检查是否所有分片都已上传完成
            boolean allChunksUploaded = true;
            for (int i = 0; i < totalChunks; i++) {
                File partFile = new File(UPLOAD_DIR + fileName + ".part" + i);
                if (!partFile.exists()) {
                    allChunksUploaded = false;
                    break;
                }
            }
            File mergedFile;
            // 合并分片文件
            if (allChunksUploaded) {
//                mergedFile = new File(UPLOAD_DIR + fileName);

                mergedFile = new File("E:\\星球项目\\shortChain\\uploads\\fileUpload.xlsx");
                for (int i = 0; i < totalChunks; i++) {
                    File partFile = new File(UPLOAD_DIR + fileName + ".part" + i);
                    FileUtils.writeByteArrayToFile(mergedFile, FileUtils.readFileToByteArray(partFile), true);
                    partFile.delete(); // 删除分片文件
                }
                log.info("上传成功");
            } else {
                log.info("上传失败");
            }
            // todo 读取不到文件  fileUpload.xlsx (系统找不到指定的文件。)
            // todo Can't open the specified file input stream from file: 'fileUpload.xlsx'
            /**
             *  try (InputStream inputStream = new FileInputStream(new File(filePath))) {
             *             EasyExcel.read(inputStream, DemoData.class, new DemoDataListener()).sheet().doRead();
             *             System.out.println("Excel file read successfully.");
             *         } catch (IOException e) {
             *             e.printStackTrace();
             *             System.err.println("Can't open the specified file input stream from file: " + filePath);
             *         }
             */
            // 应该写成两个接口 上传文件 一个读取并存储数据
            // todo 耗时2214ms
            try(InputStream inputStream = new FileInputStream(new File("E:\\星球项目\\shortChain\\uploads\\fileUpload.xlsx"))) {
                EasyExcel.read(inputStream, DemoData.class, new DemoDataListener(urlRelateService)).excelType(ExcelTypeEnum.XLSX).sheet().doRead();
                log.info("read success");
            }catch (Exception e) {
                log.error(e.getMessage());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResultUtils.success(true);
    }
}
